/*
 * Copyright (C) 2010 M. Hautle.
 * 
 * This file is part of TrackedBean.
 * 
 * TrackedBean is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any later version.
 * 
 * TrackedBean is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License along with TrackedBean. If not, see <http://www.gnu.org/licenses/>.
 */
package ch.trackedbean.internal;

import java.util.*;
import ch.msoftch.internal.*;

/**
 * Helper for services.
 * 
 * @author M. Hautle
 * @since 16.10.2010
 */
public class ServiceHelper {
    /** Flag indicating if we are running under OSGi or not. */
    private static final boolean OSGI = System.getProperty("osgi.os") != null;

    /**
     * Hidden constructor.
     */
    private ServiceHelper() {
    }

    /**
     * Returns the first service provider for the given interface.
     * 
     * @param <T> The type of the service
     * @param <D> The default implementation type
     * @param service The service interface
     * @param defaultImpl The default/fallback implementation
     * @return The service to use
     */
    public static <T, D extends T> T getService(Class<T> service, Class<D> defaultImpl) {
        final Iterator<T> i = ServiceLoader.load(service).iterator();
        if (i.hasNext())
            return i.next();
        if (OSGI)
            return OSGiServiceHelper.getService(service, defaultImpl);
        // last resort - use the default implementation
        try {
            return defaultImpl.newInstance();
        } catch (Exception e) {
            throw new TechnicalException("Error while retrieving the service implementation for " + service.getName(), e);
        }
    }
}
